package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    EditText ed_username;
    EditText ed_password;
    CheckBox chk_checkBox;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;


    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        chk_checkBox = (CheckBox) findViewById(R.id.checkBox);

        ed_username = (EditText)findViewById(R.id.ed_username);
        ed_password = (EditText)findViewById(R.id.ed_userpassword);

        sharedPreferences = getSharedPreferences("USerInfo",MODE_PRIVATE);
        editor = sharedPreferences.edit();

        String name = sharedPreferences.getString("Username","");
        if(name == null){
            chk_checkBox.setChecked(false);
        }else {
            chk_checkBox.setChecked(true);
            ed_username.setText(name);
        }


    }

    @SuppressLint("NonConstantResourceId")
    public void doClick(View view){
        switch (view.getId()){
            case R.id.btn_login:
                String name = ed_username.getText().toString().trim();
                String pass = ed_password.getText().toString().trim();
                if ("admin".equals(name) && "123456".equals(pass)){
                    if (chk_checkBox.isChecked()){
                        editor.putString("Username",name);
                        editor.commit();
                    }else {
                        editor.remove("Username");
                        editor.commit();
                    }
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                }else {
                    Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_cancel:
                ed_username.setText("");
                ed_password.setText("");
                break;
            default:
                break;
        }
    }

}
